package com.netease.nie.base.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.mybatis.spring.support.SqlSessionDaoSupport;

/**
 * 
 * @author KingsHunter
 * @createDate August 27th,2016
 *
 */
public class AbstractJdbcDao extends SqlSessionDaoSupport {
	
	@Resource
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		super.setSqlSessionFactory(sqlSessionFactory);
	}

	protected Connection getConnection() {
		SqlSessionTemplate st = (SqlSessionTemplate) getSqlSession();

		Connection connection = SqlSessionUtils.getSqlSession(
				st.getSqlSessionFactory(), st.getExecutorType(),
				st.getPersistenceExceptionTranslator()).getConnection();
		setAutoCommit(connection, true);
		return connection;
	}

	protected Connection getConnection(boolean autoCommit) {
		SqlSessionTemplate st = (SqlSessionTemplate) getSqlSession();

		Connection connection = SqlSessionUtils.getSqlSession(
				st.getSqlSessionFactory(), st.getExecutorType(),
				st.getPersistenceExceptionTranslator()).getConnection();
		setAutoCommit(connection, autoCommit);
		return connection;
	}

	private void setAutoCommit(Connection connection, boolean autoCommit) {
		try {
			connection.setAutoCommit(autoCommit);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void rollback(Connection connection) {
		try {
			connection.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void close(Connection connection) {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}
	
	protected void close(Statement statement) {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void closeOnCompletion(Statement statement) {
		if (statement != null) {
			try {
				statement.closeOnCompletion();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
